//
//  LiveViewController.m
//  penzer
//
//  Created by caiyc on 2018/9/18.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "C_LiveViewController.h"
#import "pop_func.h"
#import "pop_goodView.h"
#import "hostPopFunc.h"
#import "Dnmu_Cell.h"
#import <BDCloudMediaPlayer/BDCloudMediaPlayerController.h>
#import <BDCloudAVKit/BDCloudAVLiveSession.h>
#import "Result_popView.h"
#import <BDCloudAVKit/BDCloudAVReplayKitLiveSession.h>
#import <BDCloudAVKit/BDCloudAVCaptureSession.h>
//#import "Regist2ViewController.h"
#import "EndLiveViewController.h"
#import <GPUImage/GPUImageView.h>
#import <GPUImage/GPUImageBilateralFilter.h>
#import <GPUImage/GPUImageBrightnessFilter.h>
#import <GPUImage/GPUImageVideoCamera.h>
#import <BDCloudAVFilters/BDCloudAVNaturalBeautyFilter.h>
#import "TagView.h"
#import "ActiveTag.h"
#import "DXAlertView.h"
#import "DanmuCell.h"
#import "SRWebSocket.h"
#import <BDCloudAVBidirectRTMPKit/BDCloudAVBidirectRTMPKit.h>
static NSString * const kAccessKey = @"8643cf93d7fa4cf7897b10a7191ca73d";//8643cf93d7fa4cf7897b10a7191ca73d    //36a33862f54f47029ea0a3caedef3b3a
static NSString * const kSecretKey = @"7289921dd22e45139865d9374131c8d1";
static NSString * const kUserId = @"aa53433ed94c41cea1f3bb7168791006";
static NSString *const WeixinAppid = @"wx130fbddb55a30f80";

@interface C_LiveViewController ()<MBProgressHUDDelegate,BDCloudAVLiveSessionDelegate,PopfunsDelegate,PopfuncDelegate,UITableViewDelegate,UITableViewDataSource,TagViewDelegate,A_TagViewDelegate,DXAlertViewDelegate,BDCloudAVLiveSessionDelegate,ResultPopDelegate,SRWebSocketDelegate>
//@property(nonatomic,strong)BDCloudAVLiveSession *player;
//@property(nonatomic,strong)BDCloudAVCaptureSession*session;
@property(nonatomic,strong)BDCloudAVLiveSession*session;
//@property(nonatomic,strong)BDCloudAVBidirectRTMPSession*session;
@property(nonatomic,strong)BDCloudAVReplayKitLiveSession *repeateSession;//录屏的直播流
@property(assign)NSInteger rewad_Num;//本场活动的中奖数字
@property(assign)NSInteger cutdown_time;//抢购开始的时间
@property(assign)NSInteger end_time;//活动结束时间
@property(assign)NSInteger startlive_time;//开始直播的时间
@property(nonatomic,strong)UILabel *time_lab1;
@property(nonatomic,strong)UILabel *time_lab2;
@property(nonatomic,strong)UILabel *time_lab3;
@property(nonatomic,strong)UILabel *time_lab4;
@property(nonatomic,strong)UIImageView *like_image;
@property(nonatomic,strong)UIButton *random_Btn;
@property(nonatomic,strong)NSTimer *rand_Timer;
@property (nonatomic ,strong)dispatch_source_t timer;
@property(assign)BOOL isrobing;//是否已经在抢购
@property(nonatomic,strong)NSString *bdlive_Url;
@property(nonatomic,strong)MBProgressHUD *HUD;
@property(assign)BOOL isstart;//是否可以直播
@property(assign)BOOL isrepeate;//是否开启录屏
@property(nonatomic,strong)UIView *result_view;
@property(nonatomic,strong)UIView *bottomControlView;
@property (nonatomic, weak)GPUImageBilateralFilter  *bilateralFilter;
@property (nonatomic, weak)GPUImageBrightnessFilter *brightnessFilter;
@property (nonatomic, strong)GPUImageVideoCamera *videoCamera;
@property(nonatomic,strong)BDCloudAVNaturalBeautyFilter *beautyFilter;
@property(nonatomic,strong)UIView * diagAlertView;//开播前的确认操作视图
@property(assign)BOOL danmustatus;
@property(nonatomic,strong)UITableView *left_tab;
@property(nonatomic,strong)NSMutableArray *newsComent;//存放弹幕的数组
@property(nonatomic,strong)UIView *hostInfoView;//主播信息的视图
@property(nonatomic,strong)UIView *active_View;//
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)UIScrollView *active_ScroView;
@property(assign)NSInteger Dampage;
@property(assign)BOOL openDm;
@property(nonatomic,strong)NSDictionary *live_Detail;
@property(nonatomic,strong)NSString *active_TIme;//活动时长
@property(nonatomic,strong)NSString *goodId;//选择活动的商品
@property(nonatomic,strong)UIView *filter_View;//特效view
@property(assign)BOOL is_start;//开始直播
@property(nonatomic,strong)UILabel *dayLb;
@property(nonatomic,strong)UILabel *day_Des;
@property(nonatomic,strong)UILabel *HouseLb1;
@property(nonatomic,strong)UILabel *HouseLb2;
@property(nonatomic,strong)NSMutableArray *select_BtnArr;
@property(nonatomic,strong)NSMutableArray *goodsList;
@property(assign)NSInteger selectGoodIdx;
@property(assign)BOOL camerapostion;//摄像头位置
@property(nonatomic,strong)UIView *activeTimeView;//抢购倒计时的view
@property(assign)NSInteger activeTime;
@property(assign)BOOL openActive;
@property(nonatomic,strong)SRWebSocket *socket;
//@property(nonatomic,strong)BDCloudAVReplayKitLiveSession *recordSession;
#define margin_left 10
#define time_Lab_width 20
#define time_Lab_height 25
#define pageSize 1
@end

@implementation C_LiveViewController
-(NSMutableArray *)select_BtnArr{
    if(!_select_BtnArr){
        _select_BtnArr = [NSMutableArray array];
    }
    return _select_BtnArr;
}
-(NSMutableArray*)goodsList{
    if(!_goodsList){
        _goodsList = [NSMutableArray array];
    }
    return _goodsList;
}
-(void)bilateralFilter:(UISlider *)slide{
    NSInteger index = slide.tag;
    if(index==0){
        [self.session setBeautyBright:slide.value];
    }else if(index==1){
        [self.session setBeautyLevel:slide.value];
    }else if(index==2){
        [self.session setBeautyTone:slide.value];
    }else if(index==3){
        [self.session setColorBright:slide.value];
    }else if(index==4){
        [self.session setColorContrast:slide.value];
    }else{
         [self.session setColorSharpen:slide.value];
    }
}
-(UIView *)filter_View{
    if(!_filter_View){
        _filter_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-350, screen_width, 350)];
        _filter_View.backgroundColor =RGBA(0, 0, 0, .8);
        CGFloat itemwith = screen_width/4;
        NSArray *title = @[@"美白",@"磨皮",@"粉嫩",@"亮度",@"对比度",@"锐度"];
        UIColor *whites=[UIColor whiteColor];
            //磨皮
        for(int i =0;i<title.count;i++){
            UILabel *bilateralL = [[UILabel alloc] initWithFrame:CGRectMake(10, 50*i, 40, 45)];
            bilateralL.text = title[i];
            bilateralL.textColor = whites;
            bilateralL.font = [UIFont systemFontOfSize:12];
            [_filter_View addSubview:bilateralL];
        UISlider *bilateralSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 50*i, 250,45)
                                       ];
            bilateralSld.minimumValue = 0;
            bilateralSld.maximumValue = 1;
            if(i==3){
                bilateralSld.minimumValue = -1;
                bilateralSld.maximumValue = 1;
            }
            if(i==4){
                bilateralSld.minimumValue = 0;
                bilateralSld.maximumValue = 4;
            }
            if(i==5){
                bilateralSld.minimumValue = -4;
                bilateralSld.maximumValue = 4;
            }
            bilateralSld.tag = i;
           [bilateralSld addTarget:self action:@selector(bilateralFilter:) forControlEvents:UIControlEventValueChanged];
            [_filter_View addSubview:bilateralSld];
        }
        }
    NSArray *titles = @[@"标清",@"高清",@"超清"];//200,300,400
    for(int i =0;i<3;i++){
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.frame = CGRectMake(70*i+20, 310, 60, 40);
        btn.tag = i;
        [_filter_View addSubview:btn];
        [btn addTarget:self action:@selector(setQuaty:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _filter_View;
}
#pragma mark 设置视频上传质量
-(void)setQuaty:(UIButton *)sender{
    self.filter_View.hidden = 1;
   NSInteger quaty = 0;
     BDCloudAVVideoOutputSettings *VideoSetings = [[BDCloudAVVideoOutputSettings alloc]init];
    NSInteger index = sender.tag;
    switch (index) {
        case 0:
           // quaty = 2000000;
             [VideoSetings setBitRate:2000000];
            break;
            case 1:
           // quaty = 3000000;
             [VideoSetings setBitRate:3000000];
            break;
            case 2:
           // quaty = 4000000;
             [VideoSetings setBitRate:4000000];
            break;
        default:
            break;
    }
   
   
    BDCloudAVMovieParameter *param = [[BDCloudAVMovieParameter alloc]init];
    param.videoSettings = VideoSetings;
    NSLog(@",,,,,---%u",(unsigned int)param.videoSettings.bitRate);
    [self.session updateOutputParameter:param];
}
-(NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
        NSArray *arr1 = @[@"1分钟后",@"3分钟后",@"5分钟后",@"10分钟后"];
        NSArray *arr2 = @[@"1分钟",@"3分钟",@"5分钟",@"10分钟"];
        self.active_TIme = @"60";
        NSArray *arr3 = @[@"全部",@"数码",@"服装",@"只能设备",@"手机"];
        NSArray *arr4 = @[@"全部",@"数码",@"服装",@"只能设备",@"手机",@"衣服配饰"];
        NSArray *arr5 = @[@"全部",@"数码",@"服装"];
        NSDictionary *dic1 = @{@"title":@"设置互动开始时间",@"sid":@"1",@"data":arr1};
        NSDictionary *dic2 = @{@"title":@"设置互动时间",@"sid":@"1",@"data":arr2};
        //  [self.dataSource addObject:dic1];
        [_dataSource addObject:dic2];
    }
    return _dataSource;
}
-(UIScrollView *)active_ScroView{
    if(!_active_ScroView){
        _active_ScroView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, screen_width, screen_height-200)];
        _active_ScroView.backgroundColor = RGBA(0, 0, 0, .8);
    }
    return _active_ScroView;
}
-(UIView *)active_View{
    if(!_active_View){
        _active_View = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
        _active_View.backgroundColor = RGBA(0, 0, 0, .3);
        _active_View.hidden = 1;
        [self.view addSubview:_active_View];
        [self.view bringSubviewToFront:_active_View];
    }
    return _active_View;
}
-(NSMutableArray*)newsComent{
    if(!_newsComent){
        _newsComent = [NSMutableArray array];
    }
    return _newsComent;
}
#pragma mark 布局互动界面
-(void)initActiveView{
    [self.view bringSubviewToFront:self.active_View];
   // UIScrollView *scroView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 200, screen_width, screen_height-200)];
    [self.active_View addSubview:self.active_ScroView];
    for(UIView *views in [self.active_ScroView subviews]){
        [views removeFromSuperview];
    }
    [self.select_BtnArr removeAllObjects];
    CGFloat tagview_H = 20;
    CGFloat tagview_W = self.active_ScroView.frame.size.width;
    for(int i =0;i<self.dataSource.count;i++){
        NSDictionary *dic = self.dataSource[i];
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, tagview_H, screen_width, 40)];
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 200, 40)];
        title.text = dic[@"title"];
        title.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
        [titleView addSubview:title];
        title.textColor = [UIColor whiteColor];
        [self.active_ScroView addSubview:titleView];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(screen_width-60, 0, 40, 40);
        [btn setImage:[UIImage imageNamed:@"downs"] forState:UIControlStateNormal];
        [titleView addSubview:btn];
        
        tagview_H+=40;
        ActiveTag *tagviews =[[ActiveTag alloc]initWithFrame:CGRectMake(0, tagview_H+0, tagview_W, 0)];
        
        [tagviews setArr:dic[@"data"]];
        tagviews.tag = i;
        tagviews.delegate = self;
        [self.active_ScroView addSubview:tagviews];
        tagview_H+=tagviews.frame.size.height;
    }
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(20, tagview_H, 200, 40)];
    title.text = @"选择商品";
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    [self.active_ScroView addSubview:title];
    title.textColor = [UIColor whiteColor];
//    NSArray *goods = self.live_Detail[@"goods_list"];
     NSArray *goods = self.goodsList;
    tagview_H+=50;
    for(int i =0;i<goods.count;i++){
        NSDictionary *goodInfo = goods[i];
        UIView *goodsView = [[UIView alloc]initWithFrame:CGRectMake(0, tagview_H, screen_width, 100)];
        UIButton *slect = [UIButton buttonWithType:UIButtonTypeCustom];
        slect.frame = CGRectMake(0, 0, 50, 100);
        [slect setImage:[UIImage imageNamed:@"Oval 6"] forState:UIControlStateNormal];
          [slect setImage:[UIImage imageNamed:@"Group 7"] forState:UIControlStateSelected];
        [slect addTarget:self action:@selector(selctgoods:) forControlEvents:UIControlEventTouchUpInside];
        slect.tag = 500+i;
        [self.select_BtnArr addObject:slect];
        if(i==0){
            slect.selected = 1;
            self.goodId = goodInfo[@"goods_id"];
            
        }
    
       // goodsView.backgroundColor = [UIColor redColor];
        UIImageView *imags = [[UIImageView alloc]initWithFrame:CGRectMake(60, 10, 80, 80)];
        NSURL *url = [NSURL URLWithString:goods[i][@"thumb"]];
        [imags sd_setImageWithURL:url];
        UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(150, 10, screen_width-160, 30)];
        name.text = goodInfo[@"title"];
        name.font = [UIFont systemFontOfSize:15];
        name.textColor = [UIColor whiteColor];
        UILabel *desc = [[UILabel alloc]initWithFrame:CGRectMake(150, 40, screen_width-160, 30)];
        desc.text = [goodInfo[@"content"]isEqualToString:@""]?@"暂无":goodInfo[@"content"];
        desc.font = [UIFont systemFontOfSize:13];
        desc.textColor = [UIColor whiteColor];
        UILabel *price = [[UILabel alloc]initWithFrame:CGRectMake(150, 70, screen_width-160, 30)];
        price.text = goodInfo[@"buy_price"];
        price.font = [UIFont systemFontOfSize:18];
        price.textColor = [UIColor whiteColor];
        [goodsView addSubview:imags];
        [goodsView addSubview:name];
        [goodsView addSubview:desc];
        [goodsView addSubview:price];
        [goodsView addSubview:slect];
        [self.active_ScroView addSubview:goodsView];
        tagview_H+=100;
    }
    Regular_Btn *confirm = [Regular_Btn buttonWithType:UIButtonTypeCustom];
    confirm.frame = CGRectMake(20, tagview_H+20, screen_width-40, 50);
    confirm.backgroundColor = BUTTON_COLOR;
    [confirm setTitle:@"开启" forState:UIControlStateNormal];
    [confirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(startActive) forControlEvents:UIControlEventTouchUpInside];
    [self.active_ScroView addSubview:confirm];
    self.active_ScroView.contentSize = CGSizeMake(0, tagview_H+200);
    CGFloat orgY = screen_height-tagview_H-100;
    if(orgY<0){
        orgY = 0;
    }
    self.active_ScroView.frame = CGRectMake(0, orgY, screen_width, screen_height);
}
-(void)handleSelectATag:(NSString *)keyWord andTag:(NSInteger)index AndPindex:(NSInteger)pindex{
    //NSArray *arr2 = @[@"1分钟",@"3分钟",@"5分钟",@"10分钟"];

    if(index==0){
        //1分钟
        self.active_TIme = @"60";
    }else if (index==1){
        //
        self.active_TIme = @"180";
    }else if (index==2){
        self.active_TIme = @"300";
    }
    else{
        self.active_TIme = @"600";
    }
}
#pragma mark 连接socket
-(void)connectHost{
    NSDictionary *dic = [XTool GetDefaultInfo:HOST_USER];
    NSString *str = [NSString stringWithFormat:@"scene=room&room_no=%@&token=%@&username=%@&u_type=2",self.roomNum,dic[@"token"],dic[@"nickname"]];
    //    NSMutableString *str = [NSMutableString string];
    //    [str appendString:@"scene=room"];
    //    [str appendFormat:@"&room_no=%@",self.roomNum];
    //    [str appendFormat:@"&token=%@",dic[@"token"]];
    //     [str appendFormat:@"&username=%@",dic[@"nickname"]];
    NSLog(@"str ==%@",str);
    NSString *strs = [NSString stringWithFormat:@"%@:%@?%@",SOCKET_HOST,SOCKET_PORT,str];
    NSString *encodedValue = [strs stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:encodedValue]];
    _socket = [[SRWebSocket alloc] initWithURLRequest:request];
    _socket.delegate = self;
    [_socket open];
}
#pragma mark socket代理
//接受消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
    NSDictionary *dic =   [self StrtoJson:message];
    [self.newsComent insertObject:dic[@"mes"] atIndex:0];
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];
}
- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
    //NSLog(@"socket success==%@",webSocket);
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error
{
    // NSLog(@"socket fail==%@",error);
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
    
}
-(void)changeStr:(NSString*)str{
    // "{\"code\":\"1\",\"mes\":\"{$mes}\",\"user_name\":\"{$user_name}\"}"
    
}
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload
{
    
}

-(NSDictionary *)StrtoJson:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    return dic;
}
-(NSString *)dictiontoJson:(NSDictionary *)diction{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:diction
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}
#pragma mark 开启互动
-(void)startActive{
    self.active_View.hidden = 1;
    NSDictionary *param = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"openact",@"id":self.live_id,@"countdown_time":self.active_TIme,@"current_goodsid":self.goodId};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            [WToast showWithText:@"开启成功"];
            [self.goodsList removeObjectAtIndex:self.selectGoodIdx];
            self.openActive = 1;
            self.activeTime = [self.active_TIme integerValue]+1;
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 选择商品
-(void)selctgoods:(UIButton *)sender{
    sender.selected = !sender.selected;
    NSInteger index = sender.tag-500;
    self.selectGoodIdx = index;
    for(UIButton *btn in self.select_BtnArr){
        if(btn!=sender){
//            if(sender.tag!=btn.tag){
//                btn.selected = 0;
//            }else{
//               // btn.selected = 1;
//            }
            btn.selected = 0;
        }
    }
   NSArray *goods = self.goodsList;
    self.goodId = goods[index][@"goods_id"];
}
#pragma mark 懒加载
-(UITableView *)left_tab{
    if(!_left_tab){
        _left_tab = [[UITableView alloc]initWithFrame:CGRectMake(0, screen_height-340, screen_width, 170) style:UITableViewStylePlain];
        _left_tab.delegate = self;
        _left_tab.dataSource = self;
        _left_tab.backgroundColor = [UIColor clearColor];
        _left_tab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _left_tab.transform = CGAffineTransformMakeScale(1, -1);//翻转180
        //_left_tab.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_left_tab];
    }
    return _left_tab;
}
-(UIView *)hostInfoView{
    if(!_hostInfoView){
        NSInteger margin_Top = KISIphoneX?55:30;
        //顶部主播简介
        _hostInfoView = [[UIView alloc] init];
        _hostInfoView.frame = CGRectMake(17.5, margin_Top,176,40);
        _hostInfoView.layer.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6].CGColor;
        _hostInfoView.layer.cornerRadius = 20;
    }
    return _hostInfoView;
}
#pragma mark 互动倒计时的视图
-(UIView *)activeTimeView{
    if(!_activeTimeView){
       
            NSInteger margin_Top = KISIphoneX?55:30;
            //顶部主播简介
            _activeTimeView = [[UIView alloc] init];
            _activeTimeView.frame = CGRectMake(17.5, margin_Top,176,40);
            _activeTimeView.layer.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6].CGColor;
            _activeTimeView.layer.cornerRadius = 20;
}
     return _hostInfoView;
}
#pragma mark 左边滚动视图代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.newsComent.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"cell";
    DanmuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell =[[[NSBundle mainBundle]loadNibNamed:@"DanmuCell" owner:self options:nil]lastObject];
    }
    cell.backgroundColor = [UIColor clearColor];
    
    //    cell.backgroundColor = [UIColor clearColor];
    //    cell.textLabel.font = [UIFont systemFontOfSize:14];
    //    cell.textLabel.textColor = [UIColor darkGrayColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSString *danmu = self.newsComent[indexPath.row];
    CGFloat widthss = [XTool calculateRowWidth:danmu andHeight:26 andSize:13];
    CGRect orginRc = cell.danmView.frame;
    //  if(widthss<10)widthss+=20;
    cell.danmView.frame = CGRectMake(orginRc.origin.x,orginRc.origin.y, widthss+30, 26);
    cell.DanmuText.text = danmu;
    CGRect LabOrg = cell.DanmuText.frame;
    cell.DanmuText.frame = CGRectMake(10, 0, widthss+20+20, 26);
    cell.contentView.transform=CGAffineTransformMakeScale(1, -1);
    //    cell.textLabel.layer.cornerRadius = 11;
    //    cell.textLabel.layer.masksToBounds = 1;
    //    cell.textLabel.frame = CGRectMake(0, 0, widthss, 22);
    //    cell.textLabel.backgroundColor = RGBA(0, 0, 0, .5);
    //    cell.textLabel.text = [NSString stringWithFormat:@"%@",self.newsComent[indexPath.row]];
    //    [cell.textLabel sizeToFit];
    // cell.textLabel.backgroundColor = RGBA(0, 0, 0, .5);
    
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 29;
}
#pragma mark 开启或者关闭弹幕
-(void)opendDm{
    self.openDm = !self.openDm;
    self.left_tab.hidden = !self.openDm;
}
#pragma mark 获取弹幕数据
-(void)loadDam{
    NSDictionary *param = @{@"ctrl":@"common",@"ac":@"live",@"ta":@"get_danmu",@"act_id":self.live_id,@"page":[NSString stringWithFormat:@"%ld",(long)self.Dampage],@"psize":[NSString stringWithFormat:@"%d",pageSize]};
    NSLog(@"页数===%ld",(long)self.Dampage);
    [self loadDm:param success:^(id response) {
        if(response){
            self.Dampage++;
            NSArray *datas = response[@"data"];
            for(int i =0;i<datas.count;i++){
                [self.newsComent insertObject:datas[i][@"content"] atIndex:0];
                NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];
            }
            
        }
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)loadnewsComents{
    for(int i =0;i<10;i++){
        NSString *str = [NSString stringWithFormat:@"欢迎%d进入直播间",i];
        //  [self.newsComent addObject:str];
    }
//    [self.newsComent insertObject:@"欢迎 板扎科技 进入直播间" atIndex:0];
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
  //  [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];
    
    
}
//暂停定时器(只是暂停,并没有销毁timer)
-(void)pauseTimer{
    [self.rand_Timer setFireDate:[NSDate distantFuture]];
}
//继续计时
-(void)continueTimer{
    [self.rand_Timer setFireDate:[NSDate distantPast]];
}

//开始随机
-(void)startimer{
    //  self.random_Btn.hidden = 0;
    [self.rand_Timer fire];
}
//暂停并销毁
-(void)stopTimer{
    [self.rand_Timer invalidate];
    self.rand_Timer = nil;
}
-(NSTimer*)rand_Timer{
    if (!_rand_Timer) {
        _rand_Timer =[NSTimer scheduledTimerWithTimeInterval:0.2  target:self  selector:@selector(randoms) userInfo:nil  repeats:YES];
    }
    return _rand_Timer;
}
//开启、关闭录屏
-(void)record{
//    self.isrepeate = !self.isrepeate;
//    if(self.isrepeate==1){
//        [self.repeateSession start];
//    }else{
//        [self.repeateSession stop];
//    }
}
#pragma mark 开播前的提示确认操作
-(void)showDiagAlert{
    
    self.diagAlertView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height)];
    self.diagAlertView.backgroundColor = RGBA(0, 0, 0, .5);
    UIButton *confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    confirm.frame = CGRectMake(20, screen_height/2-55, screen_width-40, 50);
    confirm.layer.cornerRadius = 5;
    confirm.layer.masksToBounds = 1;
    confirm.backgroundColor = BUTTON_COLOR;
    [confirm setTitle:@"准备好了，开始直播" forState:UIControlStateNormal];
    [self.diagAlertView addSubview:confirm];
    
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    cancel.frame = CGRectMake(20, screen_height/2+5, screen_width-40, 50);
    cancel.layer.cornerRadius = 5;
    cancel.layer.masksToBounds = 1;
    cancel.backgroundColor = BUTTON_COLOR;
    [cancel setTitle:@"暂不开始" forState:UIControlStateNormal];
    [self.diagAlertView addSubview:cancel];
    
    [confirm addTarget:self action:@selector(confirmLive) forControlEvents:UIControlEventTouchUpInside];
    [cancel addTarget:self action:@selector(exit_live) forControlEvents:UIControlEventTouchUpInside];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.diagAlertView];
}
#pragma mark 确认开播
-(void)confirmLive{
    [self.diagAlertView removeFromSuperview];
    [self loadliveInfo];
    [self connectHost];
}
#pragma mark 退出直播间
-(void)exit_live{
     [self.diagAlertView removeFromSuperview];
//    [self.session stopPreview];
//    [self.navigationController popViewControllerAnimated:0];
}
#pragma mark 主播打开底部主播功能
#pragma mark 功能列表弹出框
-(void)openmorefunc{
    hostPopFunc *pop = [[hostPopFunc alloc]init];
    pop.delegate = self;
   // [pop show:self.danmustatus];
}
-(void)AlertView:(pop_func *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex Andtitle:(nonnull NSString *)change{
    if(buttonIndex==0){
        //分享
    }else if (buttonIndex==1){
        //开启互动
        self.active_View.hidden = 0;
       [self initActiveView];
    }else if (buttonIndex==2){
        //关闭弹幕
        UILabel *titles =(UILabel *) [alertView viewWithTag:1024+2];
        self.danmustatus = !self.danmustatus;
        [self opendDm];
        
    }else if(buttonIndex==3){
        //关闭直播
        [self close_Live];
    }
}
#pragma mark 选择美颜效果
-(void)selectFilter:(UIButton *)sender{
//    self.filter_View.hidden = 1;
    CGFloat br = 0.0f;
    CGFloat be= 0.0f;
    CGFloat to = 0.0f;
    if(sender.tag==0){
        br = 0.65;
        be = 0.80;
        to = 0.65;
    }else if (sender.tag==1){
        br = 0.6;
        be = 0.35;
        to = 0.95;
    }else if (sender.tag==2){
        br = 0.65;
        be = 0.35;
        to = 0.45;
    }else{
        br = 0.4;
        be = 0.55;
        to = 0.05;
    }
    [self.session setBeautyBright:br];//设置美白
    [self.session setBeautyLevel:be];//设置磨皮
    [self.session setBeautyTone:to];//
//    [self.session setColorBright:br];
//    [self.session setColorHue:br];
//    [self.session setColorContrast:to];
//    [self.session setColorSharpen:be];
  
   // self.beautyFilter = [[BDCloudAVNaturalBeautyFilter alloc]init];
  //  self.beautyFilter.brightLevel =br;
   // self.beautyFilter.beautyLevel = be;
  //  self.beautyFilter.toneLevel = to;
  //  [self.session addFilter:self.beautyFilter];
}
#pragma mark 买商品的弹出框
-(void)showgoods{
    self.filter_View.hidden = 0;
//    hostPopFunc *view = [[hostPopFunc alloc]init];
//    [view show];
}
-(void)viewWillAppear:(BOOL)animated{
    //进入直播间先判断用户是否完善了信息
    
}
//视频效果调整
-(void)initFilter{
    self.bottomControlView = [[UIView alloc] initWithFrame:CGRectMake(0, screen_height-200, 320, 118)];
 //   [self.view addSubview:self.bottomControlView];
    
    
//    //磨皮
//    UILabel *bilateralL = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 40, 25)];
//    bilateralL.text = @"磨皮";
//    bilateralL.font = [UIFont systemFontOfSize:12];
//    [self.bottomControlView addSubview:bilateralL];
//    
//    UISlider *bilateralSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 10, 250, 30)
//                               ];
//    bilateralSld.minimumValue = 0;
//    bilateralSld.maximumValue = 1;
//    //    bilateralSld.value = 0;
//    [bilateralSld addTarget:self action:@selector(bilateralFilter:) forControlEvents:UIControlEventValueChanged];
//    [self.bottomControlView addSubview:bilateralSld];
//    
//    
//    //美白
//    UILabel *brightnessL = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 40, 25)];
//    brightnessL.text = @"美白";
//    brightnessL.font = [UIFont systemFontOfSize:12];
//    [self.bottomControlView addSubview:brightnessL];
//    
//    UISlider *brightnessSld  = [[UISlider alloc] initWithFrame:CGRectMake(50, 40, 250, 30)
//                                ];
//    brightnessSld.minimumValue = 0;
//    brightnessSld.maximumValue = 1;
//    //    brightnessSld.value = 0;
//    [brightnessSld addTarget:self action:@selector(brightnessFilter:) forControlEvents:UIControlEventValueChanged];
//    [self.bottomControlView addSubview:brightnessSld];
}
#pragma mark 获取中奖结果
-(void)loadresult{
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"whoprize",@"id":self.live_id};
    [self weqPostHandle:params success:^(id response) {
        NSLog(@"中奖结果==%@",response);
        if(response){
            Result_popView *alert = [[Result_popView alloc]init];
            alert.delegate = self;
            NSLog(@"传递的参数......%@",response[@"data"]);
            [alert showWithData:response[@"data"] andisHost:1];

            
        }else{
            
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)loadAddress{
    //    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"member",@"op":@"address",@"ta":@"index"};
    //    [self weqPostHandle:params success:^(id response) {
    //        if(response){
    //            if([response[@"data"][@"name"]isEqualToString:@""]||[response[@"data"][@"address"]isEqualToString:@""]){
    //                Regist2ViewController *vc = [[Regist2ViewController alloc]init];
    //                [self pushSecondVC:vc];
    //            }
    //        }else{
    //            Regist2ViewController *vc = [[Regist2ViewController alloc]init];
    //            [self pushSecondVC:vc];
    //        }
    //    } failure:^(NSError *error) {
    //
    //    }];
}
-(NSString *)getMMSSFromSS:(NSInteger )totalTime{
    
    NSInteger seconds = totalTime;
    NSInteger hour = seconds/3600;
    if(hour>0){
        self.dayLb.hidden= 0;
        self.dayLb.text = [NSString stringWithFormat:@"%ld小时",hour];
        
        UILabel *timedes = (UILabel *)[self.view viewWithTag:1028];
        timedes.frame = CGRectMake(timedes.frame.origin.x, screen_height-150, 100, 20);
        // self.dayLb = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    }
    NSString *str_hour = [NSString stringWithFormat:@"%ld",seconds/3600];
    //format of minute
    NSInteger minute = (seconds%3600)/60;
    NSString *str_minute = [NSString stringWithFormat:@"%ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of minute
   // NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    if(str_minute.length>1){
        self.time_lab1.text = [str_minute substringWithRange:NSMakeRange(0, 1)];
        self.time_lab2.text =  [str_minute substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab2.text = str_minute;
    }
    //format of second
   // NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    if(str_second.length>1){
        self.time_lab3.text = [str_second substringWithRange:NSMakeRange(0, 1)];
        self.time_lab4.text =  [str_second substringWithRange:NSMakeRange(1, 1)];
    }else{
        self.time_lab3.text = @"0";
        self.time_lab4.text = str_second;
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@分钟%@秒",str_minute,str_second];
    
   // NSLog(@"format_time : %@",format_time);
    
    return format_time;
}
//直播结束
-(void)endlive{
//    if(self.repeateSession){
//        [self.repeateSession stop];
//        
//    }
    [self.session stopPreview];
    [self.session stop];
    NSDictionary *param = @{@"ctrl":@"live_merch",@"ac":@"store",@"op":@"activity",@"ta":@"activityend",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            [WToast showWithText:@"直播已结束"];
            [self performSelector:@selector(close_Live) withObject:nil afterDelay:5];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:1];
}
//抢购倒计时
-(void)cutdown{
    
    __block  NSInteger start = 0;
    
   // start = self.end_time;
    if(self.isstart==1){
        start = self.end_time;
    }else{
        start = self.startlive_time;
    }
    //0.创建队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //3.要调用的任务
    dispatch_source_set_event_handler(timer, ^{
    
        if(self.openActive==1){
            //互动倒计时
          
            if(self.activeTime>0){
               self.activeTime--;
            }else{
                self.openActive = 0;
                [self loadresult];
            }
        }
        NSLog(@"GCD-----%@",[NSThread currentThread]);
        [self loadDam];
         [self loadLikeNum];
        if(self.end_time>0){
            self.end_time--;
            [self getMMSSFromSS:self.end_time];
        }else{
            //直播已结束
            DXAlertView *alert = [[DXAlertView alloc]initWithTitle:@"提示" message:@"直播时间已到" cancelBtnTitle:@"取消" otherBtnTitle:@"确定"];
            alert.delegate = self;
            [alert show];
            [self.session stop];
            [self.session stopPreview];
            self.session = nil;
            dispatch_cancel(self.timer);
            self.timer = nil;
        }

    });
    
    //4.开始执行
    dispatch_resume(timer);
   //
    self.timer = timer;
    
}
//#pragma mark 获取弹幕
//-(void)loadnewsComents{
//    for(int i =0;i<10;i++){
//        NSString *str = [NSString stringWithFormat:@"欢迎%d进入直播间",i];
//        //  [self.newsComent addObject:str];
//    }
//    [self.newsComent insertObject:@"欢迎进入直播间" atIndex:0];
//    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//
//    [self.left_tab insertRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationTop];
//
//
//}
//获取活动的观看人数和点赞人数
-(void)loadLikeNum{
    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"total",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        SLog(@"点赞信息===%@",response);
        if(response){
            
            UILabel *like_Num = (UILabel *)[self.view viewWithTag:1025];
            like_Num.text =[NSString stringWithFormat:@"%@",response[@"data"][@"praise"]];
            UILabel *guest = (UILabel *)[self.view viewWithTag:1026];
            guest.text = [NSString stringWithFormat:@"%@",response[@"data"][@"total_member"]];
            
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)startlive{
    
}
#pragma mark 获取活动详情
-(void)loadliveInfo{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_HUD];
   _HUD.label.text = @"获取直播数据";
    //细节文字
    _HUD.detailsLabel.text = @"请耐心等待";
    NSDictionary *param = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"detail",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        
        if(response){
            self.is_start = 1;

            [self.HUD removeFromSuperview];
            [ self.goodsList addObjectsFromArray:response[@"data"][@"goods_list"]];
            self.HUD = nil;
            self.live_Detail = response[@"data"];
             self.bdlive_Url = response[@"data"][@"bdlive"];
            UILabel *label =(UILabel *)[self.hostInfoView viewWithTag:152];
            UILabel *endDes = (UILabel *)[self.view viewWithTag:1028];
            endDes.text = @"距直播结束";
            endDes.textColor = [UIColor whiteColor];
            label.text = [NSString stringWithFormat:@"房间号:%@ 粉丝:%@",response[@"data"][@"store"][@"room_number"],response[@"data"][@"anchor_list"][0][@"anchor_fans"]];//h更新主播房间号和粉丝
           
            self.rewad_Num = [response[@"data"][@"right_num"]integerValue];
            UILabel *rele_lab =(UILabel *)[self.view viewWithTag:1024];
            rele_lab.text =[NSString stringWithFormat:@"本场规则：在随机变化的数字中，最先点中%ld",(long)self.rewad_Num];
            self.startlive_time =[response[@"data"][@"start_time"]integerValue]-[response[@"data"][@"now_time"]integerValue];
            self.cutdown_time = [response[@"data"][@"countdown_time"]integerValue]-[response[@"data"][@"now_time"]integerValue];
            self.end_time =  [response[@"data"][@"end_time"]integerValue]-[response[@"data"][@"service_time"]integerValue];
            NSLog(@"z结束时间===%ld",(long)self.end_time);
             [self start_Live];
            if(self.startlive_time>0){

            }
            if(self.end_time>0&&self.startlive_time<0){

            }
            if(self.end_time<0){
             
            }
            
          
            
            
            
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)start_Live{
    [self.session start];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    self.danmustatus = 1;
    [self left_tab];
    [self cutdown];
  NSInteger margin_Top = KISIphoneX?55:30;
//    //顶部主播简介
//    UIView *hostview = [[UIView alloc] init];
//    hostview.frame = CGRectMake(17.5, margin_Top,176,40);
//    hostview.layer.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6].CGColor;
//    hostview.layer.cornerRadius = 20;
//
//
//    UIImageView *host_Icon = [[UIImageView alloc] init];
//    host_Icon.frame = CGRectMake(2,7,26,26);
//    host_Icon.layer.cornerRadius = 13;
//    host_Icon.layer.masksToBounds = 1;
//    host_Icon.image = [UIImage imageNamed:@"hosts"];
//    [hostview addSubview:host_Icon];
//
//    UILabel *nick_Lab = [[UILabel alloc] init];
//    nick_Lab.frame = CGRectMake(35,2,60,13);
//    nick_Lab.text = @"超级大熊猫";
//    nick_Lab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:11];
//    nick_Lab.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
//    nick_Lab.textAlignment = NSTextAlignmentLeft;
//    nick_Lab.alpha = 1;
//    nick_Lab.numberOfLines = 0;
//    [hostview addSubview:nick_Lab];
//
//    UILabel *room_id = [[UILabel alloc] init];
//    room_id.frame = CGRectMake(35,20,140,11);
//    room_id.text = @"房间号：2345678 粉：20w";
//    room_id.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:11];
//    room_id.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
//    room_id.textAlignment = NSTextAlignmentLeft;
//    room_id.alpha = 1;
//    room_id.numberOfLines = 0;
//    [hostview addSubview:room_id];
//
//
//
////    self.beautyFilter = [[BDCloudAVNaturalBeautyFilter alloc]init];
////    self.beautyFilter.brightLevel = 0.5;
////    self.beautyFilter.beautyLevel = 0.5;
////    self.beautyFilter.toneLevel = 0.5;
////    [self.session addFilter:self.beautyFilter];
//
////    NSString *blive_Url =self.bdlive_Url;
////    NSURL *url = [NSURL URLWithString:blive_Url];
////    self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
////    self.session.delegate = self;
////    self.session.view.frame = CGRectMake(0, 0, screen_width, screen_height);
////    self.session.view.backgroundColor = RGBA(200, 200, 200, .8);
////    [self.view addSubview:self.session.view];
////     [self.session setBeautyBright:0];
////    [self.session setBeautyLevel:0];
////   [self.session startPreview];
// //   [self.session start];
//
//    //d添加顶部主播简介
//    [self.view addSubview:hostview];
//
//    //底部的活动规则
//    UIView *botom_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-50, screen_width, 50)];
//    botom_View.backgroundColor = RGB(109, 109, 109);
//    UILabel *rule_Lab = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, 0, screen_width-70, 50)];
//    rule_Lab.textColor = [UIColor whiteColor];
//    rule_Lab.text =[NSString stringWithFormat:@"本场规则：在随机变化的数字中，最先点中%ld",(long)self.rewad_Num];;
//    rule_Lab.font = [UIFont systemFontOfSize:13];
//    rule_Lab.tag = 1024;
//    [botom_View addSubview:rule_Lab];
//
//    UIImageView *guest_NumImage = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-60, 19, 12, 12)];
//    guest_NumImage.image = [UIImage imageNamed:@"007551"];
//    [botom_View addSubview:guest_NumImage];
//
//    UILabel *guest_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, 0, 50, 50)];
//    guest_Num.textColor = [UIColor whiteColor];
//    guest_Num.text = @"0";
//    guest_Num.font= [UIFont systemFontOfSize:12];
//    [botom_View addSubview:guest_Num];
//    guest_Num.tag = 1026;
//    [self.view addSubview:botom_View];
//
//    //抢购倒计时
//    UILabel *time_text = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
//    time_text.text = @"抢购未开始";
//    time_text.textColor = [UIColor redColor];
//    time_text.font = [UIFont systemFontOfSize:13];
//    time_text.tag = 1028;
//    // [self.player.view addSubview:time_text];
//
//
//    // [self.player.view.layer addSublayer:time_text.layer];
//    [self.view addSubview:time_text];
//    //   [self.view bringSubviewToFront:time_text];
//
//    self.time_lab1 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-90, time_Lab_width, time_Lab_height)];
//    self.time_lab1.textColor = [UIColor whiteColor];
//    self.time_lab1.text = @"0";
//  //  self.time_lab1.backgroundColor = RGBA(0, 0, 0, .5);
//    self.time_lab1.font = [UIFont systemFontOfSize:20];
//    self.time_lab1.textAlignment = 1;
//    self.time_lab1.layer.cornerRadius = 5;
//    self.time_lab1.layer.masksToBounds = 1;
//    self.time_lab1.backgroundColor = BUTTON_COLOR;
//    [self.view addSubview:self.time_lab1];
//
//    self.time_lab2 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+10-5, screen_height-90, time_Lab_width, time_Lab_height)];
//    self.time_lab2.textColor = [UIColor whiteColor];
//    self.time_lab2.text = @"0";
//   // self.time_lab2.backgroundColor = RGBA(0, 0, 0, .5);
//    self.time_lab2.font = [UIFont systemFontOfSize:20];
//    self.time_lab2.textAlignment = 1;
//    self.time_lab2.layer.cornerRadius = 5;
//    self.time_lab2.layer.masksToBounds = 1;
//    self.time_lab2.backgroundColor = BUTTON_COLOR;
//    [self.view addSubview:self.time_lab2];
//
//    UILabel *mao = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+10, screen_height-90, 5, time_Lab_height-5)];
//    mao.text = @":";
//    mao.textAlignment = NSTextAlignmentCenter;
//    mao.textColor = [UIColor whiteColor];
//    mao.font = [UIFont systemFontOfSize:20];
//    [self.view addSubview:mao];
//
//    self.time_lab3 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+20, screen_height-90, time_Lab_width, time_Lab_height)];
//    self.time_lab3.textColor = [UIColor whiteColor];
//    self.time_lab3.text = @"0";
//   // self.time_lab3.backgroundColor = RGBA(0, 0, 0, .5);
//    self.time_lab3.font = [UIFont systemFontOfSize:20];
//    self.time_lab3.textAlignment = 1;
//    self.time_lab3.layer.cornerRadius = 5;
//    self.time_lab3.backgroundColor = BUTTON_COLOR;
//    self.time_lab3.layer.masksToBounds = 1;
//    [self.view addSubview:self.time_lab3];
//
//    self.time_lab4 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*3+30-5, screen_height-90, time_Lab_width, time_Lab_height)];
//    self.time_lab4.textColor = [UIColor whiteColor];
//    self.time_lab4.text = @"0";
//    self.time_lab4.backgroundColor = BUTTON_COLOR;
//   // self.time_lab4.backgroundColor = RGBA(0, 0, 0, .5);
//    self.time_lab4.font = [UIFont systemFontOfSize:20];
//    self.time_lab4.textAlignment = 1;
//    self.time_lab4.layer.cornerRadius = 5;
//    self.time_lab4.layer.masksToBounds = 1;
//    [self.view addSubview:self.time_lab4];
    UIButton *btn = (UIButton *)[self.view viewWithTag:1101];
    btn.frame = CGRectMake(screen_width-50, screen_height-160, 40, 40);
    UIButton *btn1 = (UIButton *)[self.view viewWithTag:1102];
    [btn1 removeFromSuperview];
    UILabel *lab = (UILabel *)[self.view viewWithTag:1028];
  //  [lab removeFromSuperview];
    //右边的点赞和分享元素
    UIImageView *share_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-100, 25, 25)];
    share_img.image = [UIImage imageNamed:@"Group 4 Copy 2"];
    share_img.contentMode = UIViewContentModeScaleAspectFit;
    //  [self.player.view addSubview:share_img];
    
    
    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    share_Btn.frame = CGRectMake(screen_width-50, screen_height-100, 40, 40);
    [share_Btn setImage:[UIImage imageNamed:@"Group 4 Copy 2"] forState:UIControlStateNormal];
    [share_Btn addTarget:self action:@selector(openmorefunc) forControlEvents:UIControlEventTouchUpInside];
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.view addSubview:share_Btn];
    
    
    self.like_image = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-160, 30, 30)];
    self.like_image.contentMode = UIViewContentModeScaleAspectFit;
    self.like_image.image = [UIImage imageNamed:@"礼物"];
    // [self.player.view addSubview:self.like_image];
    
    //    UILabel *like_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-130, 30, 20)];
    //    like_Num.textAlignment = 1;
    //    like_Num.textColor = [UIColor whiteColor];
    //    like_Num.text = @"10w";
    //    like_Num.font = [UIFont systemFontOfSize:13];
    //    like_Num.tag = 1025;
    //    [self.player.view addSubview:like_Num];
    
    
    UIButton *like_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    like_Btn.frame = CGRectMake(screen_width-50, screen_height-160, 40, 40);
    [like_Btn setImage:[UIImage imageNamed:@"礼物"] forState:UIControlStateNormal];
    [like_Btn addTarget:self action:@selector(showgoods) forControlEvents:UIControlEventTouchUpInside];
    //  like_Btn.backgroundColor = [UIColor redColor];
    // like_Btn.backgroundColor = [UIColor yellowColor];
    // [share_Btn setImage:[UIImage imageNamed:@"008551"] forState:UIControlStateNormal];
//    [self.view addSubview:like_Btn];
    
//    UISwitch *swiths = [[UISwitch alloc]initWithFrame:CGRectMake(screen_width-60, screen_height-220, 50, 50)];
//    [swiths addTarget:self action:@selector(record) forControlEvents:UIControlEventValueChanged];
//    [self.view addSubview:swiths];
//
//    UILabel *swithlabel = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-60, screen_height-270, 50, 50)];
//    swithlabel.text = @"录屏";
//    swithlabel.textAlignment = NSTextAlignmentCenter;
//    swithlabel.textColor = [UIColor blackColor];
//    swithlabel.font = [UIFont systemFontOfSize:14];
//    [self.view addSubview:swithlabel];
//
//
//    //随机数抽奖元素
//    self.random_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.random_Btn.frame = CGRectMake(screen_width-180, screen_height-180, 100, 100);
//    [self.random_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [self.random_Btn setTitle:@"8" forState:UIControlStateNormal];
//    self.random_Btn.titleLabel.font = [UIFont systemFontOfSize:60];
//    self.random_Btn.backgroundColor = RGB(228, 33, 17);
//    self.random_Btn.layer.cornerRadius = 50;
//    self.random_Btn.layer.masksToBounds = 1;
//    [self.random_Btn addTarget:self action:@selector(clickRandom:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.random_Btn];
//    self.random_Btn.hidden = 1;
//
//
//    //右上角关闭按钮
//
//    UIImageView *close_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-30, margin_Top, 15, 15)];
//    close_img.image = [UIImage imageNamed:@"关闭551"];
//    [self.view addSubview:close_img];
//    UIButton *close_btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    close_btn.frame = CGRectMake(screen_width-50, margin_Top, 100, 50);
//    // [close_btn setImage:[UIImage imageNamed:@"关闭551"] forState:UIControlStateNormal];
//    //[close_btn setTitle:@"关闭" forState:UIControlStateNormal];
//    [close_btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [close_btn addTarget:self action:@selector(close_Live) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:close_btn];
//    // 将播放器的 view 添加到 self 的 view 中。
//    dispatch_async(dispatch_get_main_queue(), ^{
//        //  [self.view addSubview:self.player.view];
//        //  [self.view.layer addSublayer:self.player.view.layer];
//        // [weakSelf.conversationListTableView reloadData];
//    });
//    //中奖元素
//    self.result_view = [[UIView alloc]initWithFrame:CGRectMake(screen_width/2-80, screen_height/2-80, 160, 160)];
//    self.result_view.backgroundColor = RGBA(208, 29, 27, .3);
//  //  [self.player.view addSubview:self.result_view];
//    self.result_view.hidden = 1;
//    UILabel *titles = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, 160, 20)];
//    titles.textAlignment =  1;
//    titles.text = @"恭喜";
//    titles.textColor = [UIColor whiteColor];
//    titles.font = [UIFont systemFontOfSize:14];
//    [self.result_view addSubview:titles];
//
//    UILabel *titles1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 120, 160, 20)];
//    titles1.textAlignment =  1;
//    titles1.text = @"中奖";
//    titles1.textColor = [UIColor whiteColor];
//    titles1.font = [UIFont systemFontOfSize:14];
//    [self.result_view addSubview:titles1];
//
//    [self.view addSubview:self.filter_View];
//    self.filter_View.hidden = 1;
//    [self.view bringSubviewToFront:self.filter_View];
 //   [self initFilter];
    
    //录屏直播

//    NSURL *rtmp = url;
//    NSString *userId = kUserId;
//    self.repeateSession = [[BDCloudAVReplayKitLiveSession alloc] initWithURL:url
//                                                               userId:userId];
    
    // 设置事件回调
//    self.repeateSession.delegate = self;
//    [self.repeateSession start];
    
    

    
  //  self.repeateSession enqueueSampleBuffer:<#(CMSampleBufferRef)#> type:<#(RPSampleBufferType)#>
    
    //底部的活动规则
    //    UIView *botom_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-50, screen_width, 50)];
    //    botom_View.backgroundColor = RGB(109, 109, 109);
    //    UILabel *rule_Lab = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, 0, screen_width-70, 50)];
    //    rule_Lab.textColor = [UIColor whiteColor];
    //    rule_Lab.text =@"本场规则：在随机变化的数字中，最先点中5";
    //    rule_Lab.font = [UIFont systemFontOfSize:13];
    //    rule_Lab.tag = 1024;
    //    [botom_View addSubview:rule_Lab];
    //
    //    UIImageView *guest_NumImage = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-60, 19, 12, 12)];
    //    guest_NumImage.image = [UIImage imageNamed:@"007551"];
    //    [botom_View addSubview:guest_NumImage];
    //
    //    UILabel *guest_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, 0, 50, 50)];
    //    guest_Num.textColor = [UIColor whiteColor];
    //    guest_Num.text = @"25w";
    //    guest_Num.font= [UIFont systemFontOfSize:12];
    //    [botom_View addSubview:guest_Num];
    //    guest_Num.tag = 1026;
    //    [self.view addSubview:botom_View];
    //
    //    //抢购倒计时
    //    UILabel *time_text = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    //    time_text.text = @"离抢购开始";
    //    time_text.textColor = [UIColor redColor];
    //    time_text.font = [UIFont systemFontOfSize:13];
    //    time_text.tag = 1028;
    //    // [self.player.view addSubview:time_text];
    //
    //
    //    // [self.player.view.layer addSublayer:time_text.layer];
    //    [self.view addSubview:time_text];
    //    //   [self.view bringSubviewToFront:time_text];
    //
    //    self.time_lab1 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-90, time_Lab_width, time_Lab_height)];
    //    self.time_lab1.textColor = [UIColor whiteColor];
    //    self.time_lab1.text = @"0";
    //    self.time_lab1.backgroundColor = RGBA(0, 0, 0, .5);
    //    self.time_lab1.font = [UIFont systemFontOfSize:25];
    //    self.time_lab1.textAlignment = 1;
    //    self.time_lab1.layer.cornerRadius = 5;
    //    self.time_lab1.layer.masksToBounds = 1;
    //    [self.view addSubview:self.time_lab1];
    //
    //    self.time_lab2 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+10-5, screen_height-90, time_Lab_width, time_Lab_height)];
    //    self.time_lab2.textColor = [UIColor whiteColor];
    //    self.time_lab2.text = @"0";
    //    self.time_lab2.backgroundColor = RGBA(0, 0, 0, .5);
    //    self.time_lab2.font = [UIFont systemFontOfSize:25];
    //    self.time_lab2.textAlignment = 1;
    //    self.time_lab2.layer.cornerRadius = 5;
    //    self.time_lab2.layer.masksToBounds = 1;
    //    [self.view addSubview:self.time_lab2];
    //
    //    UILabel *mao = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+10, screen_height-90, 5, time_Lab_height)];
    //    mao.text = @":";
    //    mao.textColor = [UIColor whiteColor];
    //    mao.font = [UIFont systemFontOfSize:20];
    //    [self.view addSubview:mao];
    //
    //    self.time_lab3 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+20, screen_height-90, time_Lab_width, time_Lab_height)];
    //    self.time_lab3.textColor = [UIColor whiteColor];
    //    self.time_lab3.text = @"0";
    //    self.time_lab3.backgroundColor = RGBA(0, 0, 0, .5);
    //    self.time_lab3.font = [UIFont systemFontOfSize:25];
    //    self.time_lab3.textAlignment = 1;
    //    self.time_lab3.layer.cornerRadius = 5;
    //    self.time_lab3.layer.masksToBounds = 1;
    //    [self.view addSubview:self.time_lab3];
    //
    //    self.time_lab4 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*3+30-5, screen_height-90, time_Lab_width, time_Lab_height)];
    //    self.time_lab4.textColor = [UIColor whiteColor];
    //    self.time_lab4.text = @"0";
    //    self.time_lab4.backgroundColor = RGBA(0, 0, 0, .5);
    //    self.time_lab4.font = [UIFont systemFontOfSize:25];
    //    self.time_lab4.textAlignment = 1;
    //    self.time_lab4.layer.cornerRadius = 5;
    //    self.time_lab4.layer.masksToBounds = 1;
    //    [self.view addSubview:self.time_lab4];
    //
    //    //右边的点赞和分享元素
    //    UIImageView *share_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-100, 25, 25)];
    //    share_img.image = [UIImage imageNamed:@"分享按钮551"];
    //    share_img.contentMode = UIViewContentModeScaleAspectFit;
    //    [self.view addSubview:share_img];
    //
    //
    //    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    share_Btn.frame = CGRectMake(screen_width-60, screen_height-110, 50, 50);
    //    [share_Btn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    //    // share_Btn.backgroundColor = [UIColor redColor];
    //    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    //    [self.view addSubview:share_Btn];
    //
    //
    //    self.like_image = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-160, 30, 30)];
    //    self.like_image.contentMode = UIViewContentModeScaleAspectFit;
    //    self.like_image.image = [UIImage imageNamed:@"008551"];
    //    [self.view addSubview:self.like_image];
    //
    //    UILabel *like_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-130, 30, 20)];
    //    like_Num.textAlignment = 1;
    //    like_Num.textColor = [UIColor whiteColor];
    //    like_Num.text = @"10w";
    //    like_Num.font = [UIFont systemFontOfSize:13];
    //    like_Num.tag = 1025;
    //    [self.view addSubview:like_Num];
    //
    //
    //    UIButton *like_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    like_Btn.frame = CGRectMake(screen_width-60, screen_height-170, 50, 50);
    //    [like_Btn addTarget:self action:@selector(like) forControlEvents:UIControlEventTouchUpInside];
    //    // like_Btn.backgroundColor = [UIColor yellowColor];
    //    // [share_Btn setImage:[UIImage imageNamed:@"008551"] forState:UIControlStateNormal];
    //    [self.view addSubview:like_Btn];
    //
    //
    //    //随机数抽奖元素
    //    self.random_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    self.random_Btn.frame = CGRectMake(screen_width-180, screen_height-180, 100, 100);
    //    [self.random_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //    [self.random_Btn setTitle:@"8" forState:UIControlStateNormal];
    //    self.random_Btn.titleLabel.font = [UIFont systemFontOfSize:60];
    //    self.random_Btn.backgroundColor = RGB(228, 33, 17);
    //    self.random_Btn.layer.cornerRadius = 50;
    //    self.random_Btn.layer.masksToBounds = 1;
    //    [self.random_Btn addTarget:self action:@selector(clickRandom:) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:self.random_Btn];
    //    self.random_Btn.hidden = 1;
    //
    //
    //    //右上角关闭按钮
    //    NSInteger margin_Top = KISIphoneX?55:30;
    //    UIImageView *close_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-30, margin_Top, 15, 15)];
    //    close_img.image = [UIImage imageNamed:@"关闭551"];
    //    [self.view addSubview:close_img];
    //    UIButton *close_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    close_btn.frame = CGRectMake(screen_width-50, margin_Top, 100, 50);
    //    // [close_btn setImage:[UIImage imageNamed:@"关闭551"] forState:UIControlStateNormal];
    //    //[close_btn setTitle:@"关闭" forState:UIControlStateNormal];
    //    [close_btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //    [close_btn addTarget:self action:@selector(close_Live) forControlEvents:UIControlEventTouchUpInside];
    //    [self.view addSubview:close_btn];
    //    // 将播放器的 view 添加到 self 的 view 中。
    //    dispatch_async(dispatch_get_main_queue(), ^{
    //        //  [self.view addSubview:self.player.view];
    //        //  [self.view.layer addSublayer:self.player.view.layer];
    //        // [weakSelf.conversationListTableView reloadData];
    //    });
}

-(void)tapview{
    self.active_View.hidden = 1;
    self.filter_View.hidden = 1;
}
//绑定主播信息
-(void)bindHostInfo{
    
    [self.view addSubview:self.hostInfoView];
    UIImageView *host_Icon = [[UIImageView alloc] init];
    host_Icon.frame = CGRectMake(0,0,40,40);
    host_Icon.layer.cornerRadius = 20;
    host_Icon.layer.masksToBounds = 1;
    NSDictionary *hostInfo = [XTool GetDefaultInfo:HOST_USER];
    NSURL *host_icons = [NSURL URLWithString:hostInfo[@"avatar"]];
    [host_Icon sd_setImageWithURL:host_icons placeholderImage:[UIImage imageNamed:@"logo"]];
    // host_Icon.image = [UIImage imageNamed:@"hosts"];
    [_hostInfoView addSubview:host_Icon];
    
    NSString *nick_Str = hostInfo[@"nickname"];
    CGFloat widths  =[XTool calculateRowWidth:nick_Str andHeight:15 andSize:12];
    UILabel *nick_Lab = [[UILabel alloc] init];
    nick_Lab.frame = CGRectMake(45,5,widths,15);
    nick_Lab.text = hostInfo[@"nickname"];
    nick_Lab.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:12];
    nick_Lab.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    nick_Lab.textAlignment = NSTextAlignmentLeft;
    nick_Lab.alpha = 1;
    nick_Lab.numberOfLines = 0;
    [_hostInfoView addSubview:nick_Lab];
    
    UIImageView *level_Img = [[UIImageView alloc]initWithFrame:CGRectMake(45+5+widths, 5, 35, 15)];
    level_Img.image = [UIImage imageNamed:@"Group 20"];
    // level_Img.contentMode = UIViewContentModeScaleAspectFit;
    [_hostInfoView addSubview:level_Img];
    
    UILabel *leve_Lab = [[UILabel alloc]initWithFrame:CGRectMake(45+5+widths, 5, 30, 15)];
    leve_Lab.text = @"10";
    leve_Lab.textColor=[UIColor whiteColor];
    leve_Lab.font = [UIFont systemFontOfSize:11];
    leve_Lab.textAlignment = NSTextAlignmentRight;
    [_hostInfoView addSubview:leve_Lab];
    
    UILabel *room_id = [[UILabel alloc] init];
    room_id.frame = CGRectMake(45,20,140,20);
    room_id.text = [NSString stringWithFormat:@"房间号：%@ 粉丝：0",hostInfo[@"id"]];
    room_id.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:11];
    room_id.textColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    room_id.textAlignment = NSTextAlignmentLeft;
    room_id.alpha = 1;
    room_id.tag = 152;
    room_id.numberOfLines = 0;
    [_hostInfoView addSubview:room_id];
    
   
}
#pragma mark 获取主播的最新信息
-(void)loadNewHostInfo{
    NSDictionary *params = @{@"ctrl":@"live_anchor",@"ac":@"member",@"op":@"member",@"ta":@"get_member"};
    [self weqPostHandle:params success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 初始化推流界面和推流管理器session
-(void)initSession{
    NSString *blive_Url =self.bdlive_Url;
    if(!blive_Url){
        blive_Url = @"rtmp://1111";
    }
     NSURL *url = [NSURL URLWithString:blive_Url];
    if(!self.session){
       self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
    }else{
        [self.session stopPreview];
        [self.session stop];
        self.session = nil;
        self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
    }
    self.session.delegate = self;
    self.session.view.frame = CGRectMake(0, 0, screen_width, screen_height);
    self.session.view.backgroundColor = RGBA(200, 200, 200, .8);
    [self.view insertSubview:self.session.view atIndex:0];
    [self.session startPreview];
    [self.session start];
}
#pragma mark 页面布局
-(void)initSubViews{
 NSString *blive_Url =self.live_Url;
     // NSString *blive_Url =@"rtmp://bdlive.sharepanzer.com/bddemo/live_2_Host";
    if(!blive_Url){
        blive_Url = @"rtmp://1111";
    }
    
    NSURL *url = [NSURL URLWithString:blive_Url];
    BDCloudAVCaptureSettings *capt = [[BDCloudAVCaptureSettings alloc]init];
//    [capt setCaptureVideo:1];
//    [capt setCaptureAudio:1];
//    [capt setZoomFactor:1];
   // BDCloudAVAudioOutputSettings *ops= [[BDCloudAVAudioOutputSettings defaultSettings]setBitRate:400000];
    BDCloudAVVideoOutputSettings *VideoSetings = [[BDCloudAVVideoOutputSettings alloc]init];
    [VideoSetings setBitRate:3500000];
    BDCloudAVAudioOutputSettings *AudeoSetings = [[BDCloudAVAudioOutputSettings alloc]init];
   // [AudeoSetings setBitRate:3000000];
   // capt setvide
//  self.session = [[BDCloudAVLiveSession alloc] initWithURL:url captureConfig:capt videoSettings:VideoSetings audioSettings:AudeoSetings];
    self.session = [[BDCloudAVLiveSession alloc] initWithURL:url];
    UserRole role = Host;
  //  self.session = [[BDCloudAVBidirectRTMPSession alloc] initWithURL:url role:role userId:@"5455"];
    
    self.session.view.frame = CGRectMake(0, 0, screen_width, screen_height);
    self.session.view.backgroundColor = RGBA(200, 200, 200, .8);
 //   [self.session connect];
    [self.view addSubview:self.session.view];

  //  [self.session setVideoFrameRate:50];
    [self.session startPreview];//暂不开启
   // self.session
    [self.session setAutoFoucsMode];
    [self.session setVideoFrameRate:30];
    [self.session setAutoWhiteBalance];
   // [self.session setAudioEnable:1];
  //  [self.session setMasterVolume:1.0];
  //  [self.session setMasterVolume:1];

    BDCloudAVMovieParameter *param = [[BDCloudAVMovieParameter alloc]init];
    param.videoSettings = VideoSetings;
    [self.session updateOutputParameter:param];
    [self bindHostInfo];
    //底部的活动规则
    UIView *botom_View = [[UIView alloc]initWithFrame:CGRectMake(0, screen_height-50, screen_width, 50)];
    botom_View.backgroundColor = RGB(109, 109, 109);
    UILabel *rule_Lab = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, 0, screen_width-70, 50)];
    rule_Lab.textColor = [UIColor whiteColor];
    rule_Lab.text =@"本场规则：在随机变化的数字中，最先点中";
    rule_Lab.font = [UIFont systemFontOfSize:13];
    rule_Lab.tag = 1024;
    [botom_View addSubview:rule_Lab];
    
    UIImageView *guest_NumImage = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-60, 19, 12, 12)];
    guest_NumImage.image = [UIImage imageNamed:@"007551"];
    [botom_View addSubview:guest_NumImage];
    
    UILabel *guest_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, 0, 50, 50)];
    guest_Num.textColor = [UIColor whiteColor];
    guest_Num.text = @"0";
    guest_Num.font= [UIFont systemFontOfSize:12];
    [botom_View addSubview:guest_Num];
    guest_Num.tag = 1026;
    [self.view addSubview:botom_View];
    
    //抢购倒计时
    UILabel *time_text = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 100, 20)];
    time_text.text = @"直播未开始";
    time_text.textColor = [UIColor whiteColor];
    time_text.font = [UIFont systemFontOfSize:16];
    time_text.tag = 1028;
     [self.view addSubview:time_text];

    
    CGFloat timeDesY = screen_height-90;
    
    self.dayLb = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, screen_height-120, 110, 20)];

    self.dayLb.textColor = [UIColor whiteColor];
    self.dayLb.text = @"0";
   // self.dayLb.backgroundColor = BUTTON_COLOR;
    self.dayLb.font = [UIFont systemFontOfSize:18];
    self.dayLb.textAlignment = 1;
    self.dayLb.layer.cornerRadius = 5;
    self.dayLb.textAlignment = NSTextAlignmentLeft;
    self.dayLb.layer.masksToBounds = 1;
    [self.view addSubview:self.dayLb];
    self.dayLb.hidden = 1;
//
//    self.day_Des = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+5, timeDesY, time_Lab_width, time_Lab_height)];
//
//    self.day_Des.textColor = [UIColor whiteColor];
//    self.day_Des.text = @"天";
//    self.day_Des.backgroundColor = BUTTON_COLOR;
//    self.day_Des.font = [UIFont systemFontOfSize:25];
//    self.day_Des.textAlignment = 1;
//    self.day_Des.layer.cornerRadius = 5;
//    self.day_Des.layer.masksToBounds = 1;
//    [self.view addSubview:self.day_Des];
//
//    self.HouseLb1 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, timeDesY, time_Lab_width, time_Lab_height)];
//    self.HouseLb1.textColor = [UIColor whiteColor];
//    self.HouseLb1.text = @"0";
//    self.HouseLb1.backgroundColor = BUTTON_COLOR;
//    self.HouseLb1.font = [UIFont systemFontOfSize:25];
//    self.HouseLb1.textAlignment = 1;
//    self.HouseLb1.layer.cornerRadius = 5;
//    self.HouseLb1.layer.masksToBounds = 1;
//    [self.view addSubview:self.HouseLb1];
//
//    self.HouseLb2 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+10-5, screen_height-90, time_Lab_width, time_Lab_height)];
//    self.HouseLb2.textColor = [UIColor whiteColor];
//    self.HouseLb2.text = @"0";
//    self.HouseLb2.backgroundColor = BUTTON_COLOR;
//    self.HouseLb2.font = [UIFont systemFontOfSize:25];
//    self.HouseLb2.textAlignment = 1;
//    self.HouseLb2.layer.cornerRadius = 5;
//    self.HouseLb2.layer.masksToBounds = 1;
//    [self.view addSubview:self.HouseLb2];
    
    
    
     self.time_lab1 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left, timeDesY, time_Lab_width, time_Lab_height)];
    self.time_lab1.textColor = [UIColor blackColor];
    self.time_lab1.text = @"0";
    self.time_lab1.backgroundColor = BUTTON_COLOR;
    self.time_lab1.font = [UIFont systemFontOfSize:25];
    self.time_lab1.textAlignment = 1;
    self.time_lab1.layer.cornerRadius = 5;
    self.time_lab1.layer.masksToBounds = 1;
   [self.view addSubview:self.time_lab1];
    
    self.time_lab2 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width+10-5, screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab2.textColor = [UIColor blackColor];
    self.time_lab2.text = @"0";
    self.time_lab2.backgroundColor = BUTTON_COLOR;
    self.time_lab2.font = [UIFont systemFontOfSize:25];
    self.time_lab2.textAlignment = 1;
    self.time_lab2.layer.cornerRadius = 5;
    self.time_lab2.layer.masksToBounds = 1;
    [self.view addSubview:self.time_lab2];
    
    UILabel *mao = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+10, screen_height-90, 5, time_Lab_height)];
    mao.text = @":";
    mao.textColor = [UIColor blackColor];
    mao.font = [UIFont systemFontOfSize:20];
   [self.view addSubview:mao];
    
    self.time_lab3 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*2+20, screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab3.textColor = [UIColor blackColor];
    self.time_lab3.text = @"0";
    self.time_lab3.backgroundColor = BUTTON_COLOR;
    self.time_lab3.font = [UIFont systemFontOfSize:25];
    self.time_lab3.textAlignment = 1;
    self.time_lab3.layer.cornerRadius = 5;
    self.time_lab3.layer.masksToBounds = 1;
    [self.view addSubview:self.time_lab3];
    
    self.time_lab4 = [[UILabel alloc]initWithFrame:CGRectMake(margin_left+time_Lab_width*3+30-5, screen_height-90, time_Lab_width, time_Lab_height)];
    self.time_lab4.textColor = [UIColor blackColor];
    self.time_lab4.text = @"0";
    self.time_lab4.backgroundColor = BUTTON_COLOR;
    self.time_lab4.font = [UIFont systemFontOfSize:25];
    self.time_lab4.textAlignment = 1;
    self.time_lab4.layer.cornerRadius = 5;
    self.time_lab4.layer.masksToBounds = 1;
   [self.view addSubview:self.time_lab4];
    
    
    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    share_Btn.frame = CGRectMake(screen_width-50, screen_height-100, 40, 40);
    [share_Btn setImage:[UIImage imageNamed:@"filters"] forState:UIControlStateNormal];
    [share_Btn addTarget:self action:@selector(showfilter) forControlEvents:UIControlEventTouchUpInside];
    share_Btn.tag= 1101;
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.view addSubview:share_Btn];
    //preplay
    UIButton *start = [UIButton buttonWithType:UIButtonTypeCustom];
    start.frame = CGRectMake(screen_width-50, screen_height-160, 40, 40);
    [start setImage:[UIImage imageNamed:@"preplay"] forState:UIControlStateNormal];
    [start addTarget:self action:@selector(showDiagAlert) forControlEvents:UIControlEventTouchUpInside];
    start.tag = 1102;
    // share_Btn.backgroundColor = [UIColor redColor];
    //[share_Btn setBackgroundImage:[UIImage imageNamed:@"分享按钮551"] forState:UIControlStateNormal];
    [self.view addSubview:start];
    
    
    //右边的点赞和分享元素
//    UIImageView *share_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-100, 25, 25)];
//    share_img.image = [UIImage imageNamed:@"分享按钮551"];
//    share_img.contentMode = UIViewContentModeScaleAspectFit;
//    [self.view addSubview:share_img];
//
//
//    UIButton *share_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    share_Btn.frame = CGRectMake(screen_width-60, screen_height-110, 50, 50);
//    [share_Btn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
//   [self.view addSubview:share_Btn];
//
//
//    self.like_image = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-160, 30, 30)];
//    self.like_image.contentMode = UIViewContentModeScaleAspectFit;
//    self.like_image.image = [UIImage imageNamed:@"009551"];
//    [self.view addSubview:self.like_image];
//
//    UILabel *like_Num = [[UILabel alloc]initWithFrame:CGRectMake(screen_width-40, screen_height-130, 30, 20)];
//    like_Num.textAlignment = 1;
//    like_Num.textColor = [UIColor whiteColor];
//    like_Num.text = @"10w";
//    like_Num.font = [UIFont systemFontOfSize:13];
//    like_Num.tag = 1025;
//    [self.view addSubview:like_Num];
//
//
//    UIButton *like_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    like_Btn.frame = CGRectMake(screen_width-60, screen_height-170, 50, 50);
//    [like_Btn addTarget:self action:@selector(like) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:like_Btn];
    [self.view addSubview:self.filter_View];
    self.filter_View.hidden = 1;

    
    //右上角关闭按钮
    NSInteger margin_Top = KISIphoneX?55:30;
    UIImageView *close_img = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-30, margin_Top+15, 30, 30)];
    close_img.image = [UIImage imageNamed:@"closesss"];
// /   [self.view addSubview:close_img];
    UIButton *close_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    close_btn.frame = CGRectMake(screen_width-50, margin_Top, 50, 50);
     [close_btn setImage:[UIImage imageNamed:@"closesss"] forState:UIControlStateNormal];
    //[close_btn setTitle:@"关闭" forState:UIControlStateNormal];
    [close_btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [close_btn addTarget:self action:@selector(close_Live) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:close_btn];
    
  //  NSInteger margin_Top = KISIphoneX?55:30;
    UIImageView *close_img1 = [[UIImageView alloc]initWithFrame:CGRectMake(screen_width-80, margin_Top+15, 30, 30)];
    close_img1.image = [UIImage imageNamed:@"camerap"];
  //  [self.view addSubview:close_img1];
    UIButton *close_btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    close_btn1.frame = CGRectMake(screen_width-110, margin_Top, 50, 50);
    [close_btn1 setImage:[UIImage imageNamed:@"camerap"] forState:UIControlStateNormal];
    //[close_btn setTitle:@"关闭" forState:UIControlStateNormal];
    [close_btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [close_btn1 addTarget:self action:@selector(camerapositions) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:close_btn1];
   
    dispatch_async(dispatch_get_main_queue(), ^{
      
    });
  
}
#pragma mark 切换摄像头
-(void)camerapositions{
    self.camerapostion= !self.camerapostion;
    if(self.camerapostion==1){
    [self.session setCameraPosition:AVCaptureDevicePositionBack];
    }else{
         [self.session setCameraPosition:AVCaptureDevicePositionFront];
    }
}
#pragma mark 开启l美颜调节器
-(void)showfilter{
    [self.view bringSubviewToFront:self.filter_View];
    self.filter_View.hidden = 0;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
    self.openDm = 1;
    self.Dampage = 1;
    //
    UITapGestureRecognizer *tapView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapview)];
    [self.view addGestureRecognizer:tapView];
}
//关闭直播界面
-(void)close_Live{
    if(self.is_start==0){
        [self.session stopPreview];
        self.session = nil;
    [self.navigationController popViewControllerAnimated:0];
    }else{
    DXAlertView *alert = [[DXAlertView alloc]initWithTitle:@"提示" message:@"确认关闭直播间" cancelBtnTitle:@"取消" otherBtnTitle:@"下播"];
    alert.delegate = self;
    [alert show];
    }

}
-(void)dxAlertView:(DXAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
   
    if(buttonIndex!=0){
    [self requestClose];
        if(self.session){
            [self.session stopPreview];
            [self.session stop];
          //   [self.session disconnect];
            self.session = nil;
           
          //  [self.session setAudioEnable:0];
            
            //   [self.repeateSession stop];
        }
        if(self.timer){
            dispatch_cancel(self.timer);
        }
   
    }else{
        
    }
}
#pragma mark 向服务器发起下拨请求
-(void)requestClose{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_HUD];
    _HUD.label.text = @"直播数据关闭中";
    //细节文字
    _HUD.detailsLabel.text = @"请耐心等待";
//    NSDictionary *param = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"live_close",@"act_id":self.live_id};
//    [self weqPostHandle:param success:^(id response) {
//        if(response){
//            [self.HUD removeFromSuperview];
//            EndLiveViewController *vc = [[EndLiveViewController alloc]init];
//            [self pushSecondVC:vc];
//        }
//    } failure:^(NSError *error) {
//
//    }];
    
    
    NSDictionary *params = @{@"ctrl":@"live_anchor",@"ac":@"store",@"op":@"activity",@"ta":@"downlive",@"act_id":self.live_id};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            [self.HUD removeFromSuperview];
            EndLiveViewController *vc = [[EndLiveViewController alloc]init];
            vc.live_Id = self.live_id;
            [self pushSecondVC:vc];
        }
    } failure:^(NSError *error) {
        
    }];
}
//分享
-(void)shareAction{
    
}
//点赞
-(void)like{
    NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"zan",@"id":self.live_id};
    [self weqPostHandle:param success:^(id response) {
        
        if(response){
            self.like_image.image = [UIImage imageNamed:@"009551"];
        }
    } failure:^(NSError *error) {
        
    }];
}

//用户点击随机数进行抽奖
-(void)clickRandom:(UIButton *)btn{
    
    
    NSInteger rand_Nums = [btn.titleLabel.text integerValue];
    if(rand_Nums==self.rewad_Num){
        // [WToast showWithText:@"恭喜你中奖了"];
        NSDictionary *param = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"rob",@"act_id":self.live_id};
        [self weqPostHandle:param success:^(id response) {
            
        } failure:^(NSError *error) {
            
        }];
    }
    
}

-(void)randoms{
    int y =0 +  (arc4random() % 10);
    [self.random_Btn setTitle:[NSString stringWithFormat:@"%d",y] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
